package zym.diandian.tools;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.io.IOException;
import java.io.InputStream;

public class NetUtil {

    //判断WIFI是否连接
    public static boolean isWifiConnect(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }

        return false;
    }

    //获取WIFI IP
    public static String getWifiIp(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        // 获取32位整型IP地址
        int ipAddress = wifiInfo.getIpAddress();

        // 返回整型地址转换成“*.*.*.*”地址
        return String.format("%d.%d.%d.%d", (ipAddress & 0xff), ((ipAddress >> 8) & 0xff), ((ipAddress >> 16) & 0xff), ((ipAddress >> 24) & 0xff));
    }

    //获取系统配置
    public static String getProp(String value) {
        String result = "";
        try {
            Process process = Runtime.getRuntime().exec("getprop " + value);
            result = inputStream2String(process.getInputStream());
            process.destroy();
        } catch (Exception e) {
            result = "0";
        }

        System.out.println("get prop " + value + ":" + result.trim());

        return result.trim();
    }

    public static String inputStream2String(InputStream stream) throws IOException {
        int count;
        byte buffer[] = new byte[1024];
        StringBuilder builder = new StringBuilder();
        while ((count = stream.read(buffer)) != -1) {
            builder.append(new String(buffer, 0, count));
        }
        return builder.toString().trim();
    }
}
